﻿using System;
using NHibernate;
using NHibernate.Criterion;

namespace Myotragus.Data.Criteria
{
	public class QueryBuilder : IQueryBuilder
	{
		public QueryBuilder(ISessionFactoryAdapter sessionFactory)
		{
			SessionFactory = sessionFactory;
		}

		protected ISessionFactoryAdapter SessionFactory { get; private set; }

		public IPagedQuery<TEntity> CreateQuery<TEntity>(ICriteria criteria)
		{
			return new CriteriaQuery<TEntity>(criteria);
		}

		public int Count(ICriteria criteria)
		{
			criteria.SetProjection(Projections.RowCount());
			return criteria.UniqueResult<int>();
		}

		protected ISession OpenSession()
		{
			return SessionFactory.OpenSession();
		}

		public ICriteria CreateCriteria(Type persistentType)
		{
			var session = SessionFactory.OpenSession();
			var criteria = session.CreateCriteria(persistentType);

			return criteria;
		}
	}
}